package com.wyu.notaryserver.util;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.UUID;

import com.wyu.notaryserver.exception.BizException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.mock.web.MockMultipartFile;

/**
 * @author 六味lemontea 2025-01-24
 * @version 1.0
 * @description
 */
public class Base64ToImageUtil {
    public static String saveBase64Image(String base64String) {
        // 解码Base64字符串
        byte[] imageBytes = Base64.getDecoder().decode(base64String);

        AliOSSUtil aliOSSUtil = new AliOSSUtil();
        String pictureURL = "";
        // 将字节数组写入文件
        try {
            // 将字节数组转换为 MultipartFile
            ByteArrayInputStream bais = new ByteArrayInputStream(imageBytes);
            MultipartFile multipartFile = new MockMultipartFile("图片", "图片.jpg","image/jpg",bais);

            // 上传文件
            pictureURL = aliOSSUtil.upload(multipartFile);
            System.out.println("图片已成功解码并上传");
        } catch (IOException e) {
            e.printStackTrace();
            throw new BizException("保存图片失败"); // 或者抛出自定义异常
        }
        return pictureURL;
    }
    private static String getMagicNumber(byte[] fileBytes) {
        // 提取文件前 4-8 字节
        StringBuilder magicNumber = new StringBuilder();
        for (int i = 0; i < Math.min(fileBytes.length, 8); i++) {
            magicNumber.append(java.lang.String.format("%02X", fileBytes[i])); // 转换为十六进制字符串
        }
        return magicNumber.toString();
    }

    private static String determineFileType(String magicNumber) {
        // 常见文件类型的 Magic Number
        if (magicNumber.startsWith("FFD8FF")) {
            return ".jpeg";
        } else if (magicNumber.startsWith("89504E47")) {
            return ".png";
        } else if (magicNumber.startsWith("47494638")) {
            return ".gif";
        } else if (magicNumber.startsWith("25504446")) {
            return ".pdf";
        } else if (magicNumber.startsWith("504B0304")) {
            return ".zip";
        } else {
            return "Unknown file type";
        }
    }
}
